package com.server.libs.login;

import com.alibaba.fastjson2.JSON;
import com.server.dao.MobileAppDao;
import com.server.libs.login.data.AppCache;
import com.server.pojo.MobileApp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
public class AppOline {
    @Autowired
    StringRedisTemplate redis;

    @Value("${app.keepAlivePeriod}")
    String keepAlivePeriod;

    @Autowired
    MobileAppDao mobileAppDao;

    String getSaveKey(String id){
        String saveKey = "AppOline_{id}";
        return saveKey.replace("{id}", id);
    }

    private AppCache getCache(String saveKey){
        String data = redis.opsForValue().get(saveKey);
        if (data==null) return null;
        AppCache cache = JSON.to(AppCache.class, data);
        String[] var = saveKey.split("_");
        cache.id = Integer.valueOf(var[1]);
        return cache;
    }

    public void save(AppCache appCache){
        redis.opsForValue().set(getSaveKey(appCache.id.toString()), JSON.toJSONString(appCache), Long.parseLong(keepAlivePeriod), TimeUnit.SECONDS);
        log.debug("心跳保存:{}", appCache.account);
    }

    public List<AppCache> getAll(){
        Set<String> keys = redis.keys(getSaveKey("*"));
        if (keys == null) return new ArrayList<>();
        List<String> vars = redis.opsForValue().multiGet(keys);
        List<AppCache> appCaches = new ArrayList<>();
        if (vars != null) {
            for (String var : vars) {
                appCaches.add(JSON.to(AppCache.class,var));
            }
        }
        return appCaches;
    }

    public List<MobileApp> getMobileApps() {
        List<Integer> ids = getAll().stream().map(var -> var.id).collect(Collectors.toList());
        return mobileAppDao.findByIdIn(ids);
    }

    public boolean isOline(Integer id){
        return getCache(getSaveKey(id.toString())) != null;
    }

    public void del(Integer id){
        redis.delete(getSaveKey(id.toString()));
    }
}
